package com.skar.childtacker.db;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.skar.childtacker.entity.Feed;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * User: Sergey Karyaka
 * Date: 08.12.13
 * Time: 21:59
 */
public class FeedTable {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
    private DbOpenHelper dbOpenHelper;

    public FeedTable(DbOpenHelper dbOpenHelper) {
        this.dbOpenHelper = dbOpenHelper;
    }

    public void save(Feed feed) {
        SQLiteDatabase sqLiteDatabase = dbOpenHelper.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put("start_date", dateFormat.format(feed.getStartDate()));
        contentValues.put("finish_date", dateFormat.format(feed.getFinishDate()));
        sqLiteDatabase.insert(DbOpenHelper.TABLE_NAME_FEEDS, null, contentValues);
        sqLiteDatabase.close();
    }

    public List<Feed> getAll() {
        SQLiteDatabase sqLiteDatabase = dbOpenHelper.getWritableDatabase();
        String query = "select * from " + DbOpenHelper.TABLE_NAME_FEEDS + " order by start_date desc";
        Cursor cursor = sqLiteDatabase.rawQuery(query, null);
        List<Feed> feeds = new ArrayList<Feed>();
        while (cursor.moveToNext()) {
            try {
                feeds.add(mapRows(cursor));
            } catch (ParseException e) {
                Log.e("ChTr", "", e);
            }
        }
        cursor.close();
        sqLiteDatabase.close();
        return feeds;
    }

    private Feed mapRows(Cursor cursor) throws ParseException {
        Feed feed = new Feed();
        feed.setId(cursor.getInt(cursor.getColumnIndexOrThrow("id")));
        feed.setStartDate(dateFormat.parse(cursor.getString(cursor.getColumnIndexOrThrow("start_date"))));
        feed.setFinishDate(dateFormat.parse(cursor.getString(cursor.getColumnIndexOrThrow("finish_date"))));
        return feed;
    }
}
